#include "functions.h"

int terminate(){
  //  int i;
  //  double sum_sigma = 0.0;
  
  //  for( i=0; i<number_of_dimensions; i++ )
  //    sum_sigma += sigma[ i ];

  if( number_of_evaluations > max_evaluations )
    {
      printf( "[Max_Evaluation] ");
      print_elite();
      
      return 1;
    }

  else if( termination_eps > individuals[ 0 ].function_value ){
    printf( "[Find_Result] ");
    elite_save();
    print_elite();

    return 1;
  }
  
  /*
  else if( termination_eps > sum_sigma ){

    printf( "[Convergence] ");
    print_elite(); 

    return 1;
    }
  */

  else
    return 0;

}

void print_center(){
  int i;

  printf( "CENTER:Gen.:%d:", number_of_generations);

  for( i=0; i< number_of_dimensions; i++ )
    printf( "%f\t", center[ i ] );

  printf( "\n" );
}

void print_sigma(){
  int i;

  printf( "SIGMA:Gen.:%d:", number_of_generations );

  for( i=0; i< number_of_dimensions; i++ )
    printf( "%f\t", sigma[ i ] );

  printf( "\n" );

}

// Genrate min <= x < max - 1
int get_random_integer_value( const int min, const int max ){

  return ( int ) ( ( double ) rand() / RAND_MAX * ( max - min ) + min );

}

double get_random_double_value( const double min, const double max ){

  return ( double ) rand() / RAND_MAX * ( max - min ) + min;

}

double gaussrand( const double mu, const double sigma ){

  return ( sqrt( -2 * log( get_random_double_value( 0.0, 1.0 ) ) )
	   * sin( 2 * M_PI * get_random_double_value( 0.0, 1.0 ) ) * sigma + mu );

}

void print_individuals(){
  int i, j;

  for(i = 0; i< population_size; i++){
    printf( "%d:%f\t: ", i, individuals[ i ].function_value );  

    for(j = 0; j < number_of_dimensions; j++){
      printf("%f ", individuals[ i ].design_variables[ j ]);
    }
    printf("\n");
  }
  printf("\n");
}

void print_best(){
  // individualsがソート済みであることが前提条件
  int i;
  
  if( number_of_generations == 1 )
    {
      printf( "Gen.\tEva.\t\tValue\t\tDesigin Variables\n");
    }
  
  printf( ":%5d\t%8d\t%.3e\t", number_of_generations, number_of_evaluations, individuals[ 0 ].function_value);
  
  if( msg_type == 1 )
    {
      for( i=0;i<number_of_dimensions;i++ )
	printf( "%.4f\t", individuals[ 0 ].design_variables[ i ] );
    }
  
  printf( "\n" );

}
